Grids¶

🎨 print(..., end=' ')¶

In [3]:
for i in range(4):
    print(i)
0
1
2
3
In [4]:
for i in range(4):
    print(i, end=' ')
0 1 2 3 
In [5]:
for i in range(4):
    print(i, end='**')
0**1**2**3**
In [6]:
for i in range(4):
    print(i, end='\n')
0
1
2
3

🎨 Grids¶

In [7]:
numbers = [
    [1, 2, 3],
    [4, 5, 6]
]

numbers
Out[7]:
[[1, 2, 3], [4, 5, 6]]

NOTES

  • Syntax: multiline representation of a list
  • Flat version (list of lists)
  • Draw this out
    • Visual: list of rows, row of items
    • Memory: heap, values, lists, references

🖌 Print Grid¶

In [8]:
def print_grid(grid):
    for row in grid:
        for item in row:
            print(item, end=' ')
        print()

NOTES

  • discuss the code before you run it: what will it do?
In [9]:
print_grid(numbers)
1 2 3 
4 5 6 

🖌 Make Grid¶

In [10]:
def empty_grid(num_rows, num_columns, value=None):
    new_grid = []
    for row in range(num_rows):
        new_row = []
        for column in range(num_columns):
            new_row.append(value)
        new_grid.append(new_row)
    return new_grid
In [10]:
def empty_grid(num_rows, num_columns, value=None):
    new_grid = []
    while len(new_grid) < num_rows:
        new_row = []
        while len(new_row) < num_columns:
            new_row.append(value)
        new_grid.append(new_row)
    return new_grid
In [16]:
print_grid(empty_grid(4, 6))
None None None None None None 
None None None None None None 
None None None None None None 
None None None None None None 
In [15]:
print_grid(empty_grid(4, 6, value='*'))
* * * * * * 
* * * * * * 
* * * * * * 
* * * * * * 

🖌 Read Grid¶

grid_example.txt¶

In [52]:
def readgrid(filename):
    with open(filename) as file:
        lines = file.readlines()
    
    grid = []
    
    for line in lines:
        grid.append(line.split())

    return grid
In [32]:
grid = readgrid('grid_example.txt')
print_grid(grid)
. * . ! . * . 
* . ! . ! . * 
. * . ! . * . 

🎨 Coordinates¶

In [33]:
grid = empty_grid(3, 5, value='.')

print_grid(grid)
print()

grid[0][4] = '*'
grid[1][2] = '?'
grid[2][1] = '!'

print_grid(grid)
. . . . . 
. . . . . 
. . . . . 

. . . . * 
. . ? . . 
. ! . . . 

🖌 Check Grid¶

In [39]:
def has_value(grid, row, col, value):
    if row < 0 or row >= len(grid):
        return False
    
    if col < 0 or col >= len(grid[row]):
        return False
    
    return grid[row][col] == value
In [40]:
print_grid(grid)
. . . . * 
. . ? . . 
. ! . . . 
In [41]:
has_value(grid, 0, 0, '*')
Out[41]:
False
In [42]:
has_value(grid, -1, 0, '*')
Out[42]:
False
In [38]:
has_value(grid, 1, 2, '?')
Out[38]:
True

👨🏽‍🎨 Grid Game¶

Your homework assignment will be to finish the implementation of grid_game.py.

The game logic is implemented for you. You just need to fill in a few functions that work with grids.

Have fun!

Key Ideas¶

  • Grids
    • print
    • make
    • read
    • check
  • Coordinates